define(['jquery','jquery-weui','weui','template'], function ($,Weui,Weui,Template) {
    var allowTypes = [ 'image/jpg', 'image/jpeg', 'image/png', 'image/gif' ];
    // 1024KB，也就是 1MB
    var maxSize = 1024 * 1024;
    // 图片最大宽度
    var maxWidth = 800;
    var maxHeight = 800;
    var pic_config = {
        width: 700,
        height: 700,
        quality: 1
    };
    // 最大上传图片数量
    var maxCount = 6;

    var tmpl = '<li class="weui-uploader__file weui-uploader__file_status" id="#ImgID#" style="background-image:url(#url#)"> <div class="weui-uploader__file-content"></div></li>',
        $gallery = $("#gallery"),
        $galleryImg = $("#galleryImg"),
        $uploaderInput = $("#uploaderInput"),
        $uploaderFiles = $("#uploaderFiles"),
        $galleryDelete=$(".weui-gallery__opr"),
        $previewer=$(".previewer");

    var u = navigator.userAgent;
    if(u.indexOf('Android') > -1 || u.indexOf('Adr') > -1)
    {

        $("#uploaderInput").attr('capture','camera');
    }
    $uploaderInput.on("change", function(event){

                var src, url = window.URL || window.webkitURL || window.mozURL, files = event.target.files;
                if (files.length === 0) {
                    return;
                }

                var fd =new FormData();
                for (var i = 0, len = files.length; i < len; i++) {
                    console.log(i)
                    var file = files[i];
                    var fileType = file.type;
                    var reader = new FileReader();
                //     // 如果类型不在允许的类型范围内
                    if (allowTypes.indexOf(file.type) === -1) {
                        $.toast('该类型不允许上传' + fileType, "forbidden");
                        continue;
                    }
                    // if (file.size > maxSize) {
                    //     $.toast("图片太大，不允许上传", "forbidden");
                    //     continue;
                    // }
                    if ($('#uploaderFiles > .weui-uploader__file').length >= maxCount) {
                        $.toast('最多只能上传' + maxCount + '张图片', "forbidden");
                        return;
                    }

                    // if (url) {
                    //     src = url.createObjectURL(file);
                    // } else {
                    //     src = event.target.result;
                    // }
                    //  $uploaderFiles.append($(tmpl.replace('#url#', src)));
                    // // console.log(src);

                    // // var form=document.getElementById("form1");

                    src = url.createObjectURL(file);

                    // reader.onload = function (e) {


                        var img = new Image();
                    (function (i) {
                        Controller.api.compressImage(src,pic_config,function(result){
                            console.log(result);
                            console.log(i);

                            fd.append("img["+i+"]", result);
                            $.ajax({
                                    url: "/api/Api/ajaxUploadMulti",
                                    type: "POST",
                                    data: fd,
                                    dataType : 'json',
                                    processData: false,  // 告诉jQuery不要去处理发送的数据
                                    contentType: false,   // 告诉jQuery不要去设置Content-Type请求头
                                    async: false,
                                    success: function(res){
                                       console.log(res);

                                       // $.alert(JSON.stringify(res));
                                       // if($("#pic_ids").val()=='')
                                       //     $("#pic_ids").val(res.id);
                                       // else
                                       //     $("#pic_ids").val($("#pic_ids").val()+","+res.id);
                                        var num = $('#uploaderFiles > .weui-uploader__file').length;
                                        $('.weui-uploader__info').text(num + '/' + maxCount);
                                        var $preview = $('<li class="weui-uploader__file weui-uploader__file_status" id="ImgID" style="background-image:url(' + res.data[i].url + ')"><div class="weui-uploader__file-content">0%</div></li>');
                                        $uploaderFiles.append($preview);
                                        // $uploaderFiles.append($(tmpl.replace('#url#', img.src).replace('#ImgID#',res.id)));
                                        // $uploaderFiles.append($(tmpl.replace('#url#', img.src)));
                                        // $preview.attr('id',res.id);
                                        $preview.removeClass('weui-uploader__file_status').find('.weui-uploader__file-content').remove();

                                }
                            });
                        })
                    })(i)
                }
            });

    var index;
    $uploaderFiles.on("click", "li", function(){
        index = $(this).index();
        $galleryImg.attr("style", this.getAttribute("style"));
        $galleryDelete.show();
        $gallery.fadeIn(100);
    });

    $previewer.on("click", "li", function(){
        index = $(this).index();
        $galleryImg.attr("style", this.getAttribute("style"));
        $galleryDelete.hide();
        $gallery.fadeIn(100);
    });

    $gallery.on("click", function(){
        $gallery.fadeOut(100);
    });


    $(".weui-gallery__del").click(function() {
        var picid=$uploaderFiles.find("li").eq(index).attr("id");

        $uploaderFiles.find("li").eq(index).remove();
        str=$("#pic_ids").val();
        newstr=(',' + str + ',').replace(',' + picid + ',', ',').substr(1).replace(/,$/, '');
        $("#pic_ids").val(newstr);

        // $.ajax({
        //         url: "deletePic/ids/"+picid,
        //         dataType : 'json',
        //         success: function(res){

        //     }
        // });

    })
    var Controller = {
        index: function () {
            $("#region_id").change(function() {
                id = this.value;
                // alert(id);
                // console.log('/api/index/getVillagesByRegion/region_id/' + id)
                $.ajax({
                    url: '/api/index/getVillagesByRegion/region_id/' + id,
                    dataType: 'json',
                    success: function(res){
                        option_str = ''
                        for(i= 0;i<res.length;i++)
                        {
                            option_str += '<option value="'+res[i].key+'" title="">'+res[i].value+'</option>';
                        }
                        $("#village_id").html(option_str);
                    }
                });
            });
            // $("#submit_btn").click(function(){
            //     // $.alert("自定义的消息内容");
            //     var form=document.getElementById("form1");
            //     var fd =new FormData();
            //     var title=$("#title").val()
            //     var housing_estate_id=$("#user_house_id").val();
            //     var suggestion_cat_id=$("#suggestion_cat_id").val();
            //     var content = $('#content').val();
            //     // $.alert($("#user_house_id").val());
            //     if(housing_estate_id=='0')
            //     {
            //         $.alert('请选择小区');
            //         return false;
            //     }
            //     if(suggestion_cat_id=='0')
            //     {
            //          $.alert('请选择分类');
            //         return false;
            //     }
            //     if(title=='')
            //     {
            //         $.alert('请填写标题');
            //         return false;
            //     }
            //     if(content=="")
            //     {

            //        $.alert('物业站内信',function(){
            //          $('#content').focus();
            //        });
            //         return false;
            //     }
            //     document.getElementById("form1").submit();
            //     return false;


            // })
        },

        api: {
            convertBase64UrlToBlob: function (urlData) {
                console.log(urlData);
                var arr = urlData.split(',')
                var mime = arr[0].match(/:(.*?);/)[1]
                console.log(mime)
                var bstr = atob(arr[1])
                var n = bstr.length
                var u8arr = new Uint8Array(n)
                while (n--) {
                  u8arr[n] = bstr.charCodeAt(n)
                }
                return new Blob([u8arr], { type: mime })
            },
            convertBase64UrltoFile: function(dataurl) {
                var filename = 'file'
                var arr = dataurl.split(',')
                var mime = arr[0].match(/:(.*?);/)[1]
                var suffix = mime.split('/')[1]
                var bstr = atob(arr[1])
                var n = bstr.length
                var u8arr = new Uint8Array(n)
                while (n--) {
                  u8arr[n] = bstr.charCodeAt(n)
                }
                return new File([u8arr], filename + '.' + suffix, {
                  type: mime
                })
            },
            compressImage: function(path, config, callback) {

                var img = new Image()
                img.src = path
                img.onload = function() {
                    var that = this
                    var width_ratio  = config.width / that.width;
                    var height_ratio  = config.height / that.height ;
                    if (width_ratio >= height_ratio)
                    {
                      var w = Math.min(config.width, that.width);
                        // 高度按比例计算
                      var h = that.height * (w / that.width);
                    }
                    // 源图过宽
                    else if (width_ratio <= height_ratio)
                    {

                      var h=Math.min(config.height, that.height);
                      var w=that.width *(h/that.height);
                    }
                    var quality = 0.7 // 默认图片质量为0.7
                    // 生成canvas
                    var canvas = document.createElement('canvas')
                    var ctx = canvas.getContext('2d')
                    // 创建属性节点
                    var anw = document.createAttribute('width')
                    anw.nodeValue = w
                    var anh = document.createAttribute('height')
                    anh.nodeValue = h
                    canvas.setAttributeNode(anw)
                    canvas.setAttributeNode(anh)
                    ctx.drawImage(that, 0, 0, w, h)
                    if (config.quality && config.quality <= 1 && config.quality > 0) {
                      quality = config.quality
                    }
                    var base64 = canvas.toDataURL('image/*', quality)
                    var blob = Controller.api.convertBase64UrltoFile(base64)
                    // 回调函数返回blob的值（若不需要，可直接返回base64的值）
                    callback(blob)
                }
            }
        }

    };

    return Controller;
});